package xjson

import (
	"strings"
	"unsafe"

	jsoniter "github.com/json-iterator/go"
)

type fuzzyBoolDecoder struct {
}

func (decoder *fuzzyBoolDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
	valueType := iter.WhatIsNext()
	switch valueType {
	case jsoniter.NumberValue:
		*((*bool)(ptr)) = iter.ReadFloat64() != 0
	case jsoniter.StringValue:
		str := strings.ToLower(iter.ReadString())
		switch str {
		case "", "0":
			*((*bool)(ptr)) = false
		case "true":
			*((*bool)(ptr)) = true
		case "false":
			*((*bool)(ptr)) = false
		default:
			*((*bool)(ptr)) = false
		}
	case jsoniter.BoolValue:
		*((*bool)(ptr)) = iter.ReadBool()
	case jsoniter.NilValue:
		iter.Skip()
		*((*bool)(ptr)) = false
	default:
		iter.ReportError("fuzzyBoolDecoder", "not number, string or bool")
	}
}
